package com.hitsoyauce.common;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesReader {
	private static Properties p = new Properties();
	
	static {
		try {
			p.load(PropertiesReader.class.getResourceAsStream("/config.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	};
	
	
	
	public static String getProperty(String key) {
		try {
			if (p.containsKey(key)) {
				return p.getProperty(key);
			} else {
				return "";
			}
			
		} catch (Exception e) {
			throw new RuntimeException("config.properties文件读取失败", e);
		}
	}
	
	public static void setProperty(String key, String value) {
     	FileOutputStream outputFile = null;  
        try {  
            //追加新的属性  
            p.setProperty(key, value);  
              
            //写入属性  
            outputFile = new FileOutputStream(getAbsolutePath());   
            p.store(outputFile, "");  
              
            outputFile.flush();  
        } catch (Exception e) {  
        	throw new RuntimeException("config.properties文件写入失败", e);
        } finally {
            try {
            	if (outputFile != null) {
            		outputFile.close();
            	}
            }
            catch (Exception e){ 
            	throw new RuntimeException("config.properties文件写入失败", e);
            }  
        }  
    }
	
	
	private static String getAbsolutePath() {
		String path = PropertiesReader.class.getResource("/").toString().replace("file:/", "");
		
		return path + "/config.properties";
	}
}
